package com.tongtong.exception;

import com.tt.utils.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidationException(MethodArgumentNotValidException ex) {
        // 返回第一个校验失败的字段信息
        return R.error(ex.getBindingResult().getFieldError().getDefaultMessage());
    }
    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    @ExceptionHandler(RuntimeException.class)
    public R handleCustomException(RuntimeException ex) {
        return R.error(ex.getMessage());
    }



    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public R handleException(Exception ex) {
        return R.error(ex.getMessage());
    }
}
